package com.atguigu.yygh.orders.controller;

import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.orders.service.PaymentInfoService;
import com.atguigu.yygh.orders.service.WeiXinService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @program: yygh_parent
 * @author: Mr.Zhuo
 * @create: 2022-03-19 14:28
 **/
@RestController
@RequestMapping("/api/order/weixin")
public class WeiXinController {

    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    //生成微信二维码  固定金额
    @GetMapping("/createNative/{orderId}")
    public R createNative(@PathVariable("orderId") Integer orderId) {
        Map map = weiXinService.createNative(orderId);
        return R.ok().data(map);
    }

    // 生成二维码订单之后 我们需要定时往微信接口进行调取 判断是否成功支付
    @GetMapping("queryPayStatus/{orderId}")
    public R queryPayStatus(@PathVariable("orderId") Long orderId) {

        // 首先我们需要主动定时三秒钟去查询微信后台是否成功
        Map map = weiXinService.queryPayStatus(orderId, PaymentTypeEnum.WEIXIN.name());
        if (StringUtils.isEmpty(map)) {
            // 失败返回失败数据
            return R.error().message("支付失败");
        }

        if ("SUCCESS".equals(map.get("trade_state"))) {
            // 判断成功之后进行订单数据和支付数据的更新
            paymentInfoService.paySuccess(PaymentTypeEnum.WEIXIN.getStatus(), map);
            return R.ok().message("支付成功");
        }
        //支付中
        return R.ok().message("支付中");
    }


}
